package memory.net;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.LinkedList;

public class Communicator {

	private DataInputStream inStream;
	private DataOutputStream outStream;

	private LinkedList<WrapperClass> queue = new LinkedList<WrapperClass>();
	
	public Communicator(InputStream iS, OutputStream oS) {
		inStream = new DataInputStream(iS);
		outStream = new DataOutputStream(oS);
	}
		
	public void send(WrapperClass wC) throws Exception {
		ObjectOutputStream objOutStream = new ObjectOutputStream(outStream);
		objOutStream.writeObject(wC);
		objOutStream.flush();
		outStream.flush();
	}
	
	public WrapperClass recieve() throws Exception {
		ObjectInputStream objInStream = new ObjectInputStream(inStream);
		WrapperClass recieved = (WrapperClass)objInStream.readObject();
		
		//Signal that we got the package
		outStream.writeBoolean(true);
		outStream.flush();
		
		return recieved;
	}
	
	public synchronized void addToQueue(WrapperClass wC) {
		queue.add(wC);
	}
	
	private synchronized WrapperClass pullFromQueue() {
		if(queue.size() > 0)
			return queue.get(0);
		else
			return null;
	}
	
	private synchronized void queueTopSent() {
		queue.remove(0);
	}

	public synchronized void sendFromQueue() throws Exception {
		WrapperClass toMyPlayer = pullFromQueue();
		if( toMyPlayer != null ) {
			send(toMyPlayer);
			
			//Try waiting for an answer 50 times, presume that the user won't respond get it so try and resend
			//it after that
			int i = 0;
			while(i < 50) {
			
				try {
					
					if(inStream.readBoolean()) { 
						queueTopSent();
						break;
					}
						
				}
				catch(Exception e) {}
				i++;				
				
			}
			
		}

	}
	
	
}
